package ru.urfc.portal.managers;

import java.util.List;

import ru.urfc.portal.dao.BasePersistence;
import ru.urfc.portal.dao.SpectrId;
import ru.urfc.portal.dao.filter.Filter;
import ru.urfc.portal.dao.impl.BasePersistenceImpl;
import ru.urfc.portal.model.Client;
import ru.urfc.portal.model.SpectrObjectWithCheck;
import ru.urfc.portal.ui.client.Constants;

public class BaseManager extends BasePersistenceImpl implements BasePersistence, Constants {
	
	public Client getClient(Long clientId) {
		return findById(Client.class, clientId);
	}
	
	protected SpectrId getContragentId(Long clientId) {
		return new SpectrId(getClient(clientId));
	}

	@SuppressWarnings("unchecked")
	protected <T extends SpectrObjectWithCheck> T get(Class<T> objectClass, Long clientId, Long objectId) {
		SpectrId contragentId = getContragentId(clientId);
		return (T)findById(objectClass, new SpectrId(objectId, contragentId)).check(contragentId);
	}
	
	protected <T extends SpectrObjectWithCheck> List<T> getClientDescendants(Class<T> descendantClass, Long clientId) {
		SpectrId contragentId = getContragentId(clientId);
		return find(contragentId.getBranch(), descendantClass, 
				new Filter("contragent.id", contragentId.getId()));
	}

	protected <T extends SpectrObjectWithCheck> List<T> getClientDescendants(
			Class<T> descendantClass, Long clientId, Filter filter) {
		SpectrId contragentId = getContragentId(clientId);
		Filter newFilter = new Filter(filter).addEqual("contragent.id", contragentId.getId());
		return find(contragentId.getBranch(), descendantClass, newFilter);
	}

}
